package org.example.controller;

import cn.hutool.captcha.GifCaptcha;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.example.domain.DiscussPost;
import org.example.domain.User;
import org.example.kafka.Event;
import org.example.kafka.MessageProducer;
import org.example.kafka.WKEvent;
import org.example.service.imp.DiscussServiceImp;
import org.example.service.imp.LikeServiceImp;
import org.example.service.imp.UserServiceImp;
import org.example.util.CommonParam;
import org.example.util.HutoolUtil;
import org.example.util.UserThreadLocalUtil;
import org.example.vo.IndexPageVO;
import org.example.vo.LimitPageVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Controller
public class CommonController {
    private Logger logger = LoggerFactory.getLogger(CommonController.class);
    @Autowired
    private DiscussServiceImp discussServiceImp;
    @Autowired
    private HutoolUtil hutoolUtil;
    @Autowired
    private UserThreadLocalUtil userThreadLocalUtil;
    @Autowired
    private UserServiceImp userServiceImp;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private LikeServiceImp likeServiceImp;
    @Autowired
    private MessageProducer messageProducer;
    @GetMapping({"/index.html","/error.html"})
    public String mainPage(@RequestParam(required = false) Integer current, Model model){
        IndexPageVO indexPageVO = null;
        if (current == null){
            indexPageVO = discussServiceImp.dynamicSearchByUserId(null, CommonParam.DEFAULT_PAGE, CommonParam.DEFAULT_LIMIT);
        }else {
            indexPageVO = discussServiceImp.dynamicSearchByUserId(null, current, CommonParam.DEFAULT_LIMIT);
        }
        indexPageVO.getLimitPageVO().setPath("/index.html");
        List<DiscussPost> discussPost = indexPageVO.getDiscussPost();
        if (discussPost!=null && discussPost.size()>0){
            List<Integer> discussLike = new ArrayList<>();
            for (int i = 0;i<discussPost.size();i++){
                Integer likeCount = likeServiceImp.getLikeCount(1, discussPost.get(i).getId());
                discussLike.add(likeCount);
                model.addAttribute("discussLike",discussLike);
            }
        }
        model.addAttribute("result",indexPageVO);
        return "index";
    }

    @GetMapping("user/regist.html")
    public String regist(User user){
        return "site/register";
    }
    @Value("${server.servlet.context-path}")
    private String path;
    @GetMapping("/verifyCode")
    public void createVerifyCode(Model model,HttpSession httpSession,HttpServletResponse response){
        GifCaptcha gifCaptcha = hutoolUtil.createGifCaptcha(200, 50, 4);
        httpSession.setAttribute(CommonParam.VERIFY_CODE_SYMBOL,gifCaptcha.getCode());
        try {
            response.getOutputStream().write(gifCaptcha.getImageBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @RequestMapping("/common/SecurityAccessException")
    public String securityAccessException(){
        return "error/403";
    }

    /**
     * 用来生成一个网页图片
     * @param webLocation
     * @return
     */
    @PostMapping("/generate/web/image")
    @ResponseBody
    public Integer generateWebImage(String webLocation){
        if (hutoolUtil.stringIsEmpty(webLocation)){
            return 0;
        }
        //用户发送一个ajax请求  需要做网页的生成 我们就别在这里做了 因为生成图片需要花费时间 不让用户等 我们可以 利用kafka处理一下
        WKEvent wkEvent = new WKEvent();
        wkEvent.setTopic(CommonParam.KAFKA_TOPIC_WK_GENERATE_IMAGE);
        wkEvent.setWebLocation(webLocation);//如何给一个错误的网站怎么办？ 额 不管拉
        User user = userThreadLocalUtil.get();
        wkEvent.setUserId(user.getId());
        messageProducer.wkGenerateWebImage(wkEvent);
        return 1;
    }

    @Value("${wk.generate.image.location}")
    private String wkGenerateImageLocation;
    @ResponseBody
    @RequestMapping("/download/generate/image")
    public void downloadGenerateImage(HttpServletResponse response){
        //当用户生成一个图片后 我们需要给用户返回生成图片 生成图片名字在redis中存储 key是：wk_generate_image_userid  value是一些图片名字
        //这里有个问题 因为 生成图片需要等待 但ajax很快就发送下载请求 可能图片还没有生成 所以获取不到图片  我在这里等一下
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        User user = userThreadLocalUtil.get();
        String imageName = (String) redisTemplate.opsForSet().pop(CommonParam.REDIS_WK_GENERATE_IMAGE_SYMBOL + user.getId());//默认一次性生成一个
        File file = new File(wkGenerateImageLocation+imageName);
        long length = file.length();
        try {
            InputStream inputStream = new FileInputStream(file);
            byte[] result = new byte[(int)length];
            inputStream.read(result);
            inputStream.close();
            //读取完毕后 可以写入response
            response.setCharacterEncoding("UTF-8");
            response.setContentType("image/png");
            response.setHeader("Content-disposition","attachment;filename="+imageName);
//            response.setContentType("application/octet-stream");
//            response.setHeader("Content-disposition", "attachment;filename=" + imageName);
            response.getOutputStream().write(result);
            //可以使用springMVC提供的下载组件
        } catch (Exception e) {
            logger.error("下载失败");
        }
    }
}
